package com.mikufufu.blog.controller.system;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.mikufufu.blog.common.annotation.Anonymous;
import com.mikufufu.blog.common.cache.*;
import com.mikufufu.blog.common.entity.AjaxResult;
import com.mikufufu.blog.service.PermissionService;
import com.mikufufu.blog.utils.FileUtils;
import com.mikufufu.blog.utils.IpUtil;
import com.mikufufu.blog.utils.SpringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import com.sun.management.OperatingSystemMXBean;

import java.lang.management.RuntimeMXBean;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/cache")
@Api(tags = "缓存模块")
public class CacheController {

    @Autowired
    private PermissionService permissionService;

    @Anonymous
    @GetMapping("/flush")
    @ApiOperation(value = "清空缓存", notes = "清空所有的缓存")
    public AjaxResult<Boolean> flush() {
        return AjaxResult.status(RedisCache.flushAll());
    }

    @GetMapping("/flushStorage")
    @ApiOperation(value = "清空存储服务桶的缓存", notes = "清空存储服务桶的缓存")
    public AjaxResult<Boolean> flushStorage() {
        return AjaxResult.status(StorageCache.flushAll());
    }

    @GetMapping("/flushSysSetting")
    @ApiOperation(value = "清空系统设置的缓存", notes = "清空系统设置的缓存")
    public AjaxResult<Boolean> flushAll() {
        return AjaxResult.status(SysSettingCaChe.flushAll());
    }

    @GetMapping("/flushUser")
    @ApiOperation(value = "清空用户的缓存", notes = "清空用户的缓存")
    public AjaxResult<Boolean> flushUser() {
        return AjaxResult.status(UserCache.flushAll());
    }

    @GetMapping("/flushPermission")
    @ApiOperation(value = "清空权限的缓存", notes = "清空权限的缓存")
    public AjaxResult<Boolean> flushPermission() {
        permissionService.cleanRolePermission();
        return AjaxResult.status(PermissionCache.flushAll());
    }

    @GetMapping("/add")
    public AjaxResult<String> add(String value) {
        RedisCache.sendMsg("demoTopic", value);
        return AjaxResult.data(value);
    }

    @GetMapping("/flushNav")
    @ApiOperation(value = "清空导航的缓存", notes = "清空导航的缓存")
    public AjaxResult<Boolean> flushNav() {
        return AjaxResult.status(NavCache.flushAll());
    }

    @GetMapping("/ping")
    @ApiOperation(value = "测试ping", notes = "测试ping")
    public AjaxResult<Boolean> ping(String address) throws Exception {
        List<String> list = JSON.parseObject("[\"111\",\"222\"]", new TypeReference<List<String>>(){}.getType());
        log.info("111=={}",list);
        return AjaxResult.data("test",IpUtil.ping(address));
    }

    @GetMapping("/lang")
    public AjaxResult<Void> lang() {
        return AjaxResult.success("test");
    }


    @GetMapping("/demo")
    public AjaxResult<Boolean> demo() throws UnknownHostException {
        log.info(System.getProperty("os.name"));
        log.info(System.getProperty("os.arch"));
        log.info(System.getProperty("os.version"));
        log.info(System.getProperty("user.dir"));
        log.info(System.getProperty("user.name"));
        log.info(System.getProperty("user.home"));
        log.info(System.getProperty("java.version"));
        log.info(System.getProperty("java.vm.version"));
        InetAddress localHost = InetAddress.getLocalHost();
        log.info(localHost.getHostAddress());
        log.info(localHost.getHostName());
//        Map<String, String> getenv = System.getenv();
//        getenv.forEach((k, v) -> {
//            log.info("key:{},value:{}", k, v);
//        });
        Runtime runtime = Runtime.getRuntime();
        log.info("总内存：{}", FileUtils.convertFileSize(runtime.totalMemory()));
        log.info("空闲内存：{}", FileUtils.convertFileSize(runtime.freeMemory()));
        log.info("已使用的内存：{}", FileUtils.convertFileSize(runtime.totalMemory() - runtime.freeMemory()));
        log.info("最大内存：{}", FileUtils.convertFileSize(runtime.maxMemory()));
        log.info("处理器数量：{}", runtime.availableProcessors());
        // 系统内存信息
        MemoryMXBean memoryMxBean = ManagementFactory.getMemoryMXBean();
        // 初始内存，单位为MB
        long totalMemory = memoryMxBean.getHeapMemoryUsage().getInit();
        long maxMemory = memoryMxBean.getHeapMemoryUsage().getMax();
        // 已使用内存，单位为MB
        long usedMemory = (runtime.totalMemory() - runtime.freeMemory());
        log.info("初始内存：{}", FileUtils.convertFileSize(totalMemory));
        log.info("已使用内存：{}", FileUtils.convertFileSize(usedMemory));
        log.info("最大内存：{}", FileUtils.convertFileSize(maxMemory));
        // 系统CPU信息
        OperatingSystemMXBean osMxBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
        long totalPhysicalMemorySize = osMxBean.getTotalPhysicalMemorySize();
        long freePhysicalMemorySize = osMxBean.getFreePhysicalMemorySize();
        long usedPhysicalMemorySize = totalPhysicalMemorySize - freePhysicalMemorySize;
        // 操作系统名称
        String osName = osMxBean.getName();
        // 处理器数量
        int processors = osMxBean.getAvailableProcessors();
        // 系统运行时间和进程ID
        RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
        // 运行时间（毫秒）
        long uptime = runtimeMxBean.getUptime();
        // 进程ID
        long pid = Long.parseLong(runtimeMxBean.getName().split("@")[0]);
        log.info("操作系统：{}", osName);
        log.info("处理器数量：{}", processors);
        log.info("运行时间：{}", uptime);
        log.info("进程ID：{}", pid);
        log.info("总物理内存：{}", FileUtils.convertFileSize(totalPhysicalMemorySize));
        log.info("已使用物理内存：{}", FileUtils.convertFileSize(usedPhysicalMemorySize));
        log.info("剩余物理内存：{}", FileUtils.convertFileSize(freePhysicalMemorySize));
        log.info("系统启动时间：{}", SpringUtils.getStartupTime());
        return AjaxResult.status(true);
    }
}
